<template>
  <div class="role-manage-container">
    <!-- 搜索筛选区 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="角色名称">
          <el-input v-model="searchForm.name" placeholder="请输入角色名称" clearable />
        </el-form-item>

        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态">
            <el-option label="启用" value="1" />
            <el-option label="禁用" value="0" />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮区 -->
    <div class="action-bar">
      <div style="display: flex;justify-content: flex-end">
        <el-button type="primary" @click="addRole">
          <i class="el-icon-plus"></i> 新增角色
        </el-button>
      </div>
    </div>

    <!-- 角色列表 -->
    <el-table
        :data="roleList"
        stripe
        border
        highlight-current-row
        style="width: 100%">

      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="roleName" label="角色名称" />
      <el-table-column prop="roleDescription" label="角色描述" />
      <el-table-column prop="status" label="状态" width="100">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
            {{ scope.row.status === 1 ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180" />
      <el-table-column label="操作" width="220">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="editRole(scope.row)">编辑</el-button>
          <el-button type="text" size="small" @click="setPermissions(scope.row)">权限配置</el-button>
          <el-button type="text" size="small" style="color: #f56c6c" @click="deleteRole(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页控件 -->
    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pagination.current"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pagination.size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total">
    </el-pagination>

    <!-- 新增/编辑角色对话框 -->
    <el-dialog :visible.sync="roleDialogVisible" title="角色管理">
      <el-form :model="roleForm" :rules="roleRules" ref="roleFormRef" label-width="120px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="roleForm.roleName" :disabled="roleForm.id" />
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDescription">
          <el-input type="textarea" v-model="roleForm.roleDescription" :rows="4" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="roleForm.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="roleDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveRole">保存</el-button>
      </div>
    </el-dialog>

    <!-- 权限配置对话框（核心修改：使用多选框） -->
    <el-dialog :visible.sync="permissionDialogVisible" title="权限配置">
      <div style="margin-bottom: 20px;">
        <span style="font-weight: bold;">角色：{{ currentRole.roleName || '未选择角色' }}</span>
      </div>

      <!-- 权限多选框组（4个顶级权限） -->
      <el-checkbox-group v-model="checkedPermissionIds" class="permission-checkbox-group">
        <el-checkbox
            v-for="perm in allPermissions"
            :key="perm.id"
            :label="perm.id"
            class="permission-checkbox"
        >
          <div class="permission-info">
            <div class="permission-name">{{ perm.permissionName }}</div>
            <div class="permission-desc">{{ perm.permissionDescription }}</div>
          </div>
        </el-checkbox>
      </el-checkbox-group>

      <div slot="footer" class="dialog-footer">
        <el-button @click="permissionDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="savePermissions">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { api } from "@/api";

export default {
  name: "RoleManage",
  data() {
    return {
      // 搜索表单
      searchForm: {
        name: '', // 角色名称搜索
        status: null // 状态筛选（1启用，0禁用）
      },

      // 角色列表数据
      roleList: [],

      // 分页信息
      pagination: {
        current: 1, // 当前页
        size: 10, // 每页条数
        total: 0 // 总条数
      },

      // 所有权限（4个顶级权限）
      allPermissions: [],

      // 权限配置相关
      permissionDialogVisible: false, // 权限配置弹窗
      currentRole: {}, // 当前操作的角色
      checkedPermissionIds: [], // 选中的权限ID

      // 新增/编辑角色相关
      roleDialogVisible: false, // 角色弹窗
      roleForm: {
        id: null,
        roleName: '',
        roleDescription: '',
        status: 1 // 默认启用
      },

      // 角色表单验证规则
      roleRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 2, max: 20, message: '角色名称长度在 2-20 个字符之间', trigger: 'blur' }
        ],
        roleDescription: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          { min: 5, max: 100, message: '角色描述长度在 5-100 个字符之间', trigger: 'blur' }
        ]
      }
    };
  },

  created() {
    // 页面加载时初始化数据
    this.fetchRoleList(); // 获取角色列表
    this.fetchAllPermissions(); // 获取所有权限（4个顶级权限）
  },

  methods: {
    // 1. 角色列表相关方法
    async fetchRoleList() {
      try {
        const params = {
          searchRoleName: this.searchForm.name,
          status: this.searchForm.status,
          page: this.pagination.current,
          pageSize: this.pagination.size
        };
        const res = await api.user.roleList(params);
        this.roleList = res.data.records || [];
        this.pagination.total = res.data.total || 0;
      } catch (error) {
        console.error('获取角色列表失败:', error);
        this.$message.error('获取角色列表失败，请重试');
      }
    },

    // 2. 权限相关方法
    async fetchAllPermissions() {
      try {
        const res = await api.user.getAllPermissions();
        this.allPermissions = res.data || [];
      } catch (error) {
        console.error('获取权限列表失败:', error);
        this.$message.error('获取权限列表失败');
      }
    },

    // 打开权限配置弹窗并加载角色已有权限
    async setPermissions(role) {
      this.currentRole = { ...role };
      this.permissionDialogVisible = true;

      try {
        // 获取角色已有的权限ID
        const res = await api.user.getRolePermissions(role.id);
        this.checkedPermissionIds = res.data || [];
      } catch (error) {
        console.error('获取角色权限失败:', error);
        this.$message.error('加载角色权限失败');
        this.checkedPermissionIds = [];
      }
    },

    // 保存权限配置
    async savePermissions() {
      if (!this.currentRole.id) {
        this.$message.error('角色信息异常');
        return;
      }

      try {
        await api.user.saveRolePermissions(this.currentRole.id, this.checkedPermissionIds);
        this.$message.success('权限配置保存成功');
        this.permissionDialogVisible = false;
      } catch (error) {
        console.error('保存权限失败:', error);
        this.$message.error(error.response?.data?.msg || '保存权限失败');
      }
    },

    // 3. 角色增删改方法
    addRole() {
      this.roleForm = {
        id: null,
        roleName: '',
        roleDescription: '',
        status: 1
      };
      this.roleDialogVisible = true;
    },

    editRole(role) {
      this.roleForm = { ...role };
      this.roleDialogVisible = true;
    },

    async saveRole() {
      this.$refs.roleFormRef.validate(async (valid) => {
        if (valid) {
          try {
            if (this.roleForm.id) {
              // 更新角色
              await api.user.updateRole(this.roleForm);
              this.$message.success('角色更新成功');
            } else {
              // 新增角色
              await api.user.addRole(this.roleForm);
              this.$message.success('角色创建成功');
            }
            this.roleDialogVisible = false;
            this.fetchRoleList(); // 刷新列表
          } catch (error) {
            console.error('保存角色失败:', error);
            this.$message.error(error.response?.data?.msg || '保存角色失败');
          }
        }
      });
    },

    async deleteRole(role) {
      this.$confirm(`确定要删除角色"${role.roleName}"吗？删除后不可恢复`, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await api.user.deleteRole(role.id);
          this.$message.success('角色删除成功');
          this.fetchRoleList();
        } catch (error) {
          console.error('删除角色失败:', error);
          this.$message.error(error.response?.data?.msg || '删除角色失败');
        }
      }).catch(() => {
        // 取消删除
      });
    },

    // 4. 分页和搜索方法
    handleSearch() {
      this.pagination.current = 1;
      this.fetchRoleList();
    },

    resetSearch() {
      this.searchForm = { name: '', status: null };
      this.pagination.current = 1;
      this.fetchRoleList();
    },

    handleSizeChange(size) {
      this.pagination.size = size;
      this.fetchRoleList();
    },

    handleCurrentChange(current) {
      this.pagination.current = current;
      this.fetchRoleList();
    }
  },
};
</script>

<style scoped>
.role-manage-container {
  padding: 20px;
}
.search-card {
  margin-bottom: 20px;
}
.action-bar {
  margin-bottom: 20px;
}
.permission-checkbox-group {
  max-height: 400px;
  overflow-y: auto;
  padding: 10px;
}
.permission-checkbox {
  display: block;
  margin-bottom: 15px;
  padding: 10px;
  border: 1px solid #f0f0f0;
  border-radius: 4px;
}
.permission-name {
  font-weight: 500;
  margin-bottom: 5px;
}
.permission-desc {
  color: #666;
  font-size: 12px;
}
.el-pagination {
  margin-top: 20px;
  text-align: right;
}
</style>
